import otplib from "otplib";
import qrcode from "qrcode";
import React, { useState, useEffect } from "react";

const RotatingAuth = () => {
  const [secret, setSecret] = useState("");
  const [token, setToken] = useState("");
  const [isValid, setIsValid] = useState(false);
  const [qrcodeUrl, setQrcodeUrl] = useState("");
  useEffect(() => {
    // 生成秘钥
    const secret = otplib.authenticator.generateSecret();
    setSecret(secret); // 生成谷歌认证码的链接
    const otpauthUrl = otplib.authenticator.keyuri(
      "your-email@example.com",
      "Your App Name",
      secret
    );
    // 生成二维码图片
    qrcode.toDataURL(
      otpauthUrl,
      { errorCorrectionLevel: "H" },
      (error, imageUrl) => {
        if (error) {
          console.error("生成二维码失败:", error);
          return;
        }
        setQrcodeUrl(imageUrl);
      }
    );
  }, []);
  const handleTokenChange = (event) => {
    setToken(event.target.value);
  };
  const handleVerifyToken = () => {
    // 验证认证码
    const isValid = otplib.authenticator.check(token, secret);
    setIsValid(isValid);
  };
  return (
    <div>
      <h1>登录前旋转认证功能</h1> <img src={qrcodeUrl} alt="谷歌认证二维码" />{" "}
      <p>生成的谷歌认证码: {otplib.authenticator.generate(secret)}</p>{" "}
      <p>请登录并输入谷歌认证码验证身份</p>{" "}
      <input
        type="text"
        value={token}
        onChange={handleTokenChange}
        placeholder="输入认证码"
      />{" "}
      <button onClick={handleVerifyToken}>验证认证码</button>{" "}
      <p>认证码是否有效: {isValid ? "有效" : "无效"}</p>
    </div>
  );
};

export default RotatingAuth;
